package com.sto.stoapp.camera;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.camera.CameraOperation.OnPreviewListener;
import com.sto.stoapp.entity.CameraEntity;
import com.sto.stoapp.manager.SoundManager;
import com.sto.stoapp.widget.BaseActivity;

/**
 * 拍照功能
 * 
 * @author hb
 * 
 */
public class CameraActivity extends BaseActivity {
	private Button buttonClick;
	private SurfaceHolder m_holder;
	private SurfaceView surfaceView;
	private boolean isClick = false;

	/** Called when the activity is first created. */
	@SuppressWarnings("deprecation")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);// 没有标题
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏
		this.getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// 拍照过程屏幕一直处于高亮
		// // 设置手机屏幕朝向，一共有7种
		// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);

		setContentView(R.layout.camera);

		surfaceView = (SurfaceView) findViewById(R.id.preview);
		buttonClick = (Button) findViewById(R.id.buttonClick);
		CameraOperation.instance().startIsOver();
		m_holder = surfaceView.getHolder();
		m_holder.setKeepScreenOn(true);
		m_holder.addCallback(new surfaceCallback());
		m_holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

		buttonClick.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (isClick) {
					return;
				} else {
					CameraOperation.instance().autofocus();
					isClick = true;
					buttonClick.setEnabled(false);
					buttonClick.setVisibility(View.GONE);
					try {
						Thread.sleep(600);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					CameraOperation.instance().endIsOver();
				}
			}
		});
		buttonClick.setFocusableInTouchMode(true);
		buttonClick.requestFocus();

		// 监听获取图片
		CameraOperation.instance().setOnPreviewListener(
				new OnPreviewListener() {

					@Override
					public void onPreviewListener(byte[] data) {
						savePicture(data);
					}
				});
	}

	@Override
	protected void onPause() {
		super.onPause();
		CameraOperation.instance().stopPreview();
		m_holder = null;
		isClick = false;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		CameraOperation.instance().autofocus();
		return super.onTouchEvent(event);
	}

	/**
	 * 摄像头的回调类
	 * 
	 * @author Administrator
	 * 
	 */
	private class surfaceCallback implements Callback {
		public void surfaceChanged(SurfaceHolder holder, int format, int width,
				int height) {
			// CameraOperation.instance().startPreview(width, height);
		}

		public void surfaceCreated(SurfaceHolder holder) {
			CameraOperation.instance().initialPreview(holder);

		}

		public void surfaceDestroyed(SurfaceHolder holder) {
			CameraOperation.instance().stopPreview();
		}
	}

	/**
	 * 保存图片
	 * 
	 * @param data
	 */
	public void savePicture(byte[] data) {
		try {

			// 拍照声音
			SoundManager.getInstance(this).playPhotoSound();

			// 防止420报java.lang.OutOfMemoryError: bitmap size exceeds VM
			// budget的错误
			// if (new Build().MODEL.contains(HttpUtil.MOBIL_TYPE_420)) {
			// BitmapFactory.Options options = new Options();
			// options.inDither = true; /* 进行图片抖动处理 */
			// options.inPreferredConfig = null; /* 设置让解码器以最佳方式解码 */
			// options.inSampleSize = 4; /* 图片长宽方向缩小倍数 */
			// bitmapPicture = BitmapFactory.decodeByteArray(data, 0,
			// data.length, options);
			// } else {
			// bitmapPicture = BitmapFactory.decodeByteArray(data, 0,
			// data.length);
			// }
			// // 将图片设置为宽243，高324，在这儿就可以实现图片的大小缩放
			// Bitmap resize = Bitmap.createScaledBitmap(bitmapPicture, 320,
			// 240,
			// true);

			// 做好旋转与大小之后，重新创建位图，0-width宽度上显示的区域，高度类似
			// Bitmap b = Bitmap.createBitmap(resize, 0, 0, 320, 240, m, true);

			Bitmap b = Bytes2Bimap(data);
			Matrix m = new Matrix();
			m.setRotate(90); // 逆时针旋转90度
			b = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), m,
					true);

			CameraEntity entity = new CameraEntity();
			entity.setDraw(comp(b));
			Intent pictureIntent = new Intent();
			pictureIntent.putExtra("bitmapPicture", entity);
			setResult(RESULT_OK, pictureIntent);

		} catch (OutOfMemoryError e) {
			e.printStackTrace();
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			finish();
		}
	}
	
	@Override
	public void onBackPressed() {
	    Intent pictureIntent = new Intent();
        setResult(RESULT_OK, pictureIntent);
        super.onBackPressed();
	}
	public Bitmap Bytes2Bimap(byte[] b) {
		if (b.length != 0) {
			return BitmapFactory.decodeByteArray(b, 0, b.length);
		} else {
			return null;
		}
	}
	/**
	 * 图片按比例大小压缩
	 * 
	 * @param image
	 * @return
	 */

	private Bitmap comp(Bitmap image) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		if (baos.toByteArray().length / 1024 > 1024) {// 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, 50, baos);// 这里压缩50%，把压缩后的数据存放到baos中
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;

		float hh = 320f;// 小图
		float ww = 240f;

		// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;// be=1表示不缩放
		if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;// 设置缩放比例
		newOpts.inPreferredConfig = Config.RGB_565;// 降低图片从ARGB888到RGB565
		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		isBm = new ByteArrayInputStream(baos.toByteArray());
		bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		return bitmap;// 压缩好比例大小后再进行质量压缩
	}
}